import TMapApp from './TMapApp';
import VGE from '../../VGE';

export class Camera {
	constructor(viewer) {
		this.viewer = viewer;
	}

	/**
	 * 查询视角参数
	 * @returns {Promise<{heading: *|{getFreeCameraOptions}, lon: *, pitch: *, lat: *, height: *}>}
	 */
	async getCameraParams(original = true) {
		try {
			const map = this.viewer;
			const pitch = map.getPitch();
			const rotation = +map.getRotation();
			const center = map.getCenter();
			const zoom = map.getZoom();
			const result = {
				lon: center.lng,
				lat: center.lat,
				height: 0,
				heading: rotation,
				pitch,
				zoom
			};

			if (!original) {
				result.heading = (360 + result.heading) % 360;
				result.height = 0.09 * Math.exp((31.849 - zoom) / 1.496) + 500;
				result.original = 'VGE-CAMERA';
			}

			return result;
		} catch (e) {
			console.error(e.message);
		}
	}

	/**
	 * 飞到给定视角
	 * @param cameraParams
	 * @param duration
	 * @returns {Promise<void>}
	 */
	async flyTo(cameraParams, duration = 1) {
		if (!VGE.util.validateCameraParams(cameraParams)) return;
		try {
			const map = this.viewer;
			let { lon, lat, height, heading, pitch, zoom } = cameraParams;

			if (cameraParams.original === 'VGE-CAMERA') {
				// 腾讯地图为火星坐标系需要转换,腾讯无法异步加载转换工具
				zoom = zoom || 31.849 - Math.log((height + 500) / 0.09) * 1.496;
			}

			const cam = { zoom, center: [lat, lon], rotation: heading, pitch };
			map.easeTo(cam);
		} catch (e) {
			console.error(e.message);
		}
	}

	/**
	 * 主视角
	 * @returns {Promise<void>}
	 */
	async homeView() {
		this.flyTo(TMapApp.homeViewParams);
	}
}
